# src/service/transaction_service.py
from src.db.transaction_db import (
    create_transaction,
    get_transactions_by_buyer,
    update_transaction_status,
    get_transaction_by_id
)
from src.db.artwork_db import get_artwork_by_id
from src.db.user_db import get_user_by_id
from src.utils.logger import get_logger

logger = get_logger(__name__)

def create_order(buyer_id: int, artwork_id: int) -> tuple[str | None, str]:
    """
    创建订单（购买艺术品）
    返回：(交易ID/None, 提示信息)
    """
    # 1. 校验买家身份
    buyer = get_user_by_id(buyer_id)
    if not buyer or buyer["user_role"] != "买家":
        logger.warning(f"买家身份无效（buyer_id: {buyer_id}）")
        return None, "仅买家可创建订单"
    
    # 2. 校验艺术品
    artwork = get_artwork_by_id(artwork_id)
    if not artwork:
        return None, "艺术品不存在或已下架"
    
    # 3. 校验卖家（不能购买自己的艺术品）
    seller_id = artwork["owner_id"]
    if buyer_id == seller_id:
        logger.warning(f"不能购买自己的艺术品（buyer_id: {buyer_id}, seller_id: {seller_id}）")
        return None, "不能购买自己发布的艺术品"
    
    # 4. 创建交易（初始状态：待付款）
    transaction_id = create_transaction(
        buyer_id=buyer_id,
        seller_id=seller_id,
        artwork_id=artwork_id,
        amount=artwork["price"]
    )
    
    if transaction_id:
        return transaction_id, "订单创建成功，请尽快付款"
    else:
        return None, "订单创建失败"

def pay_order(transaction_id: str) -> tuple[bool, str]:
    """
    支付订单（状态：待付款 → 待收货）
    返回：(是否成功, 提示信息)
    """
    # 1. 校验交易存在性
    transaction = get_transaction_by_id(transaction_id)
    if not transaction:
        return False, "交易不存在"
    
    # 2. 校验当前状态（仅"待付款"可支付）
    if transaction["status"] != "待付款":
        logger.warning(f"订单状态异常（transaction_id: {transaction_id}, 当前状态：{transaction['status']}）")
        return False, f"订单当前状态为{transaction['status']}，无法支付"
    
    # 3. 更新交易状态
    success = update_transaction_status(transaction_id, "待收货")
    if success:
        return True, "订单支付成功，等待卖家发货"
    else:
        return False, "支付失败，请重试"

def cancel_order(transaction_id: str) -> tuple[bool, str]:
    """
    取消订单（仅"待付款"状态可取消）
    返回：(是否成功, 提示信息)
    """
    # 1. 校验交易存在性
    transaction = get_transaction_by_id(transaction_id)
    if not transaction:
        return False, "交易不存在"
    
    # 2. 校验当前状态（仅"待付款"可取消）
    if transaction["status"] != "待付款":
        logger.warning(f"订单状态异常（transaction_id: {transaction_id}, 当前状态：{transaction['status']}）")
        return False, f"订单当前状态为{transaction['status']}，无法取消"
    
    # 3. 更新交易状态
    success = update_transaction_status(transaction_id, "已取消")
    if success:
        return True, "订单已成功取消"
    else:
        return False, "取消订单失败，请重试"

def confirm_receipt(transaction_id: str) -> tuple[bool, str]:
    """
    确认收货（状态：待收货 → 交易完成）
    返回：(是否成功, 提示信息)
    """
    # 1. 校验交易存在性
    transaction = get_transaction_by_id(transaction_id)
    if not transaction:
        return False, "交易不存在"
    
    # 2. 校验当前状态（仅"待收货"可确认）
    if transaction["status"] != "待收货":
        logger.warning(f"订单状态异常（transaction_id: {transaction_id}, 当前状态：{transaction['status']}）")
        return False, f"订单当前状态为{transaction['status']}，无法确认收货"
    
    # 3. 更新交易状态
    success = update_transaction_status(transaction_id, "交易完成")
    if success:
        return True, "已确认收货，交易完成"
    else:
        return False, "确认收货失败，请重试"

def get_buyer_orders(buyer_id: int, status: str = None) -> tuple[list, str]:
    """
    获取买家订单列表（支持按状态筛选）
    返回：(订单列表, 提示信息)
    """
    # 1. 校验买家身份
    buyer = get_user_by_id(buyer_id)
    if not buyer or buyer["user_role"] != "买家":
        logger.warning(f"买家身份无效（buyer_id: {buyer_id}）")
        return [], "仅买家可查看订单"
    
    # 2. 获取订单并补充关联信息（艺术品+卖家）
    transactions = get_transactions_by_buyer(buyer_id, status)
    for trans in transactions:
        # 补充艺术品信息
        artwork = get_artwork_by_id(trans["artwork_id"])
        if artwork:
            trans["artwork_info"] = {
                "title": artwork["title"],
                "creator": artwork["creator"],
                "price": artwork["price"],
                "category": artwork["category"]
            }
        
        # 补充卖家信息
        seller = get_user_by_id(trans["seller_id"])
        if seller:
            trans["seller_info"] = {
                "username": seller["username"],
                "real_name": seller["real_name"]
            }
    
    return transactions, "获取订单列表成功"